﻿using DevExpress.XtraEditors;
using Lamex.Base;
using Lamex.Interface;
using Lamex.Library;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Lamex.mMachine.UI
{
    public partial class frmMAC_Resource_nonWorkday : frmBaseChild
    {
        DataTable dt_Dept = null;
        string IsEdit = "";
        public frmMAC_Resource_nonWorkday()
        {
            InitializeComponent();
        }

        private void frmMAC_Resource_nonWorkday_Load(object sender, EventArgs e)
        {
            base.InitButtons();
            LoadDept();
            HideCOntrol();
            gridControl1.UseEmbeddedNavigator = true;
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshView();
        }
        public override void DoView(IButtonInfo sender)
        {
            RefreshView();
        }
        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }
        public override void DoSave(IButtonInfo sender)
        {
            Save();
        }
        public override void DoEdit(IButtonInfo sender)
        {
            SetVGridControl();
        }
        private void gridView1_DoubleClick(object sender, EventArgs e)
        {
            SetVGridControl();
        }
        public override void DoDelete(IButtonInfo sender)
        {
            int iRow = gridView1.FocusedRowHandle;
            if (iRow < 0)
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("请选择需要删除的数据！", "提示", MessageBoxButtons.OK);
                return;
            }
            DialogResult dr = DevExpress.XtraEditors.XtraMessageBox.Show("确定要删除所选数据吗？", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
            if (dr == DialogResult.Yes)
            {
                string strDept = gridView1.GetRowCellDisplayText(iRow, "DEPARTMENT").ToString();//部门
                string strnoWorkDay = gridView1.GetRowCellDisplayText(iRow, "nonWORK_DATE").ToString();//非工作日
                string sqlDel = @" DELETE FROM [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List] 
                WHERE DEPARTMENT='" + strDept + "' AND nonWORK_DATE='" + strnoWorkDay + "'";
                BaseBuildSql.ExecuteNonQuery(sqlDel);
                XtraMessageBox.Show("删除成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                RefreshView();
            }
        }
        public override void DoAdd(IButtonInfo sender)
        {
            cbDept_Add.Text = "";
            dt_Start.Text = "";
            dt_End.Text = "";
            ce_End.Checked = false;
            ce_NoWork.Checked = false;
            cbDept_Add.Enabled = true;
            dt_Start.Enabled = true;
            //dt_End.Enabled = true;
            ce_End.Enabled = true;
            ce_NoWork.Enabled = true;
            IsEdit = "Add";
            LoadDept_Add();
        }
        private void HideCOntrol()
        {
            cbDept_Add.Enabled = false;
            dt_Start.Enabled = false;
            dt_End.Enabled = false;
            ce_End.Enabled = false;
            ce_NoWork.Enabled = false;
            cbDept_Add.Text = "";
            dt_Start.Text = "";
            dt_End.Text = "";
            ce_End.Checked = false;
            ce_NoWork.Checked = false;
        }
        private void Save()
        {
            string strDept = cbDept_Add.Text;
            string strStartTime = dt_Start.Text;
            string strEndTime = dt_End.Text;
            string strWorkFlag = ce_NoWork.Checked ? "1" : "0";
            string strBatchFlag = ce_End.Checked ? "1" : "0";
            if (string.IsNullOrEmpty(strDept))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("分厂或部门不能为空！", "提示", MessageBoxButtons.OK);
                return;
            }
            if (string.IsNullOrEmpty(strStartTime))
            {
                DevExpress.XtraEditors.XtraMessageBox.Show("非工作日日期不能为空！", "提示", MessageBoxButtons.OK);
                return;
            }
            try
            {

                if (IsEdit == "Add")
                {
                    if (ce_End.Checked)
                    {
                        if (string.IsNullOrEmpty(strEndTime))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("结束日期不能为空！", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        DateTime dt1 = Convert.ToDateTime(strStartTime);
                        DateTime dt2 = Convert.ToDateTime(strEndTime);
                        if (dt2 < dt1)
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("结束日期不能小于非工作日日期！", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        while (dt1 <= dt2)
                        {
                            if (IsExist(strDept, dt1.ToString()))
                            {
                                DevExpress.XtraEditors.XtraMessageBox.Show("非工作日期已存在，不允许新增！", "提示", MessageBoxButtons.OK);
                                return;
                            }
                            if (strDept.ToUpper() == "ALL")
                            {
                                for (int i = 0; i < dt_Dept.Rows.Count; i++)
                                {
                                    if (dt_Dept.Rows[i]["DEPARTMENT"].ToString().ToUpper() == "ALL")
                                        continue;
                                    InsertTable(dt_Dept.Rows[i]["DEPARTMENT"].ToString(), dt1, strWorkFlag, strBatchFlag);
                                }
                            }
                            else
                            {
                                InsertTable(strDept, dt1, strWorkFlag, strBatchFlag);
                            }

                            dt1 = dt1.AddDays(1);
                        }
                    }
                    else
                    {
                        if(IsExist(strDept,strStartTime))
                        {
                            DevExpress.XtraEditors.XtraMessageBox.Show("非工作日期已存在，不允许新增！", "提示", MessageBoxButtons.OK);
                            return;
                        }
                        if (strDept.ToUpper() == "ALL")
                        {
                            for (int i = 0; i < dt_Dept.Rows.Count; i++)
                            {
                                if (dt_Dept.Rows[i]["DEPARTMENT"].ToString().ToUpper() == "ALL")
                                    continue;
                                InsertTable(dt_Dept.Rows[i]["DEPARTMENT"].ToString(), Convert.ToDateTime(strStartTime), strWorkFlag, strBatchFlag);
                            }
                        }
                        else
                        {
                            InsertTable(strDept, Convert.ToDateTime(strStartTime), strWorkFlag, strBatchFlag);
                        }
                    }
                    XtraMessageBox.Show("新增成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    HideCOntrol();
                    RefreshView();
                }
                if (IsEdit == "Edit")
                {
                    string sqlUpdate = @"UPDATE [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List] 
                    SET nonWORK_FLAG=" + strWorkFlag + " WHERE DEPARTMENT='" + strDept + "' AND nonWORK_DATE='" + strStartTime + "'";
                    BaseBuildSql.ExecuteNonQuery(sqlUpdate);
                    XtraMessageBox.Show("修改成功！", "提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                    HideCOntrol();
                    RefreshView();
                }
            }
            catch (Exception ex)
            {
                XtraMessageBox.Show(ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }

        }
        private void InsertTable(string strDept, DateTime dt1, string noWorkDay, string isBatch)
        {
            string sql_Insert = @"INSERT INTO [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List] ([DEPARTMENT]
                                                      ,[nonWORK_DATE]
                                                      ,[nonWORK_FLAG]
                                                      ,[BATCH_FLAG]
                                                      ,[UPDATE_TIME]
                                                      ,[UPDATE_USER]
	                                                  )
                                                VALUES('" + strDept + "','" + dt1 + "'," + noWorkDay + "," + isBatch + ",GETDATE(),'" + Lamex.Common.Loginer.CurrentUser.AccountName + "')";
            BaseBuildSql.ExecuteNonQuery(sql_Insert);
        }

        private void RefreshView()
        {
            string sql = "";
            if (cbDept_View.Text == "" || cbDept_View.Text.ToUpper() == "ALL")
            {
                sql = @"SELECT [DEPARTMENT]
                          ,[nonWORK_DATE]
                          ,[nonWORK_FLAG]
                          ,[BATCH_FLAG]
                          ,[UPDATE_TIME]
                          ,[UPDATE_USER]
                      FROM [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List] ORDER BY UPDATE_TIME DESC";
            }
            else
            {
                sql = @"SELECT [DEPARTMENT]
                          ,[nonWORK_DATE]
                          ,[nonWORK_FLAG]
                          ,[BATCH_FLAG]
                          ,[UPDATE_TIME]
                          ,[UPDATE_USER]
                      FROM [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List] WHERE DEPARTMENT='" + cbDept_View.Text + "' ORDER BY UPDATE_TIME DESC";
            }
            DataTable dt = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);
            gridControl1.DataSource = dt;
            gridView1.OptionsView.ColumnAutoWidth = false;
            gridView1.BestFitColumns();
        }
        private void LoadDept()
        {
            string sql = @"SELECT  [DEPARTMENT]  FROM [LamexMES_FAMA].[dbo].[MT_Resource_Dept_List]";
            dt_Dept = Lamex.Base.BaseBuildSql.GetDataTableBySql(sql);
            cbDept_View.Text = "";
            cbDept_View.Properties.Items.Clear();
            if (dt_Dept.Rows.Count > 0)
            {
                for (int i = 0; i < dt_Dept.Rows.Count; i++)
                {
                    cbDept_View.Properties.Items.Add(dt_Dept.Rows[i]["DEPARTMENT"].ToString());
                }
            }
        }
        private void LoadDept_Add()
        {
            cbDept_Add.Text = "";
            cbDept_Add.Properties.Items.Clear();
            if (dt_Dept.Rows.Count > 0)
            {
                for (int i = 0; i < dt_Dept.Rows.Count; i++)
                {
                    cbDept_Add.Properties.Items.Add(dt_Dept.Rows[i]["DEPARTMENT"].ToString());
                }
            }
        }
        private void SetVGridControl()
        {
            HideCOntrol();
            IsEdit = "Edit";
            ce_NoWork.Enabled = true;
            int iRow = gridView1.FocusedRowHandle;
            string strDept = gridView1.GetRowCellDisplayText(iRow, "DEPARTMENT").ToString();//部门
            string strnoWorkDay = gridView1.GetRowCellDisplayText(iRow, "nonWORK_DATE").ToString();//非工作日
            bool boolnonWorkFlag = gridView1.GetRowCellDisplayText(iRow, "nonWORK_FLAG").ToString() == "Checked" ? true : false;
            cbDept_Add.Text = strDept;
            dt_Start.Text = strnoWorkDay;
            ce_NoWork.Checked = boolnonWorkFlag;
        }
        private bool IsExist(string strDept, string noWorkDay)
        {
            noWorkDay = Convert.ToDateTime(noWorkDay).ToString("yyyy-MM-dd");
            string sql = @"SELECT  * FROM [LamexMES_FAMA].[dbo].[Resource_nonWorkday_List]
            WHERE DEPARTMENT='" + strDept + "' AND nonWORK_DATE='" + noWorkDay + "'";
            DataTable dataTable = BaseBuildSql.GetDataTableBySql(sql);
            if (dataTable.Rows.Count > 0)
                return true;
            else
                return false;
        }

        private void frmMAC_Resource_nonWorkday_Resize(object sender, EventArgs e)
        {
            splitContainerControl1.SplitterPosition = this.Width / 4 * 3;
        }

        private void ce_End_CheckedChanged(object sender, EventArgs e)
        {
            dt_End.Enabled = ce_End.Checked ? true : false;
        }
    }
}
